package com.yxq.mdt.app.modules.video.ui.fragment;


import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseFragment;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.modules.personal.bean.MyPersonalBean;
import com.yxq.mdt.app.modules.video.adapter.ChatAdapter;
import com.yxq.mdt.app.modules.video.bean.AdvertBean;
import com.yxq.mdt.app.modules.video.bean.ChannelListBean;
import com.yxq.mdt.app.modules.video.bean.ChatListDataBean;
import com.yxq.mdt.app.modules.video.bean.ChatTabBean;
import com.yxq.mdt.app.modules.video.bean.MLUserList;
import com.yxq.mdt.app.modules.video.bean.VideoChatBean;
import com.yxq.mdt.app.modules.video.bean.VideoChatListBean;
import com.yxq.mdt.app.modules.video.model.MainVideoModel;
import com.yxq.mdt.app.modules.video.presenter.IMainVideoContract;
import com.yxq.mdt.app.modules.video.presenter.MainVideoPresenter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 密聊
 */
public class MainVideoChatFragment extends BaseFragment<MainVideoPresenter> implements IMainVideoContract.View {
    public static final String EXTRA_TEXT = "extra_text";
    @BindView(R.id.video_chat_recycler)
    RecyclerView videoChatRecycler;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    ChatAdapter chatAdapter;
    @BindView(R.id.error_view)
    RelativeLayout errorView;

    @Override
    protected int attachLayoutId() {
        return R.layout.fragment_video_chat;
    }

    @Override
    protected MainVideoPresenter getPresenter() {
        return new MainVideoPresenter(this, new MainVideoModel());
    }

    @Override
    public void initView(View view) {
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            page = 1;
            mPresenter.getChannelConfig(1);
        });
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            page++;
            mPresenter.getMlList(page, 20, 1, null, null, null);
        });
        videoChatRecycler.setLayoutManager(new LinearLayoutManager(mContext));
        MyPersonalBean personalBean = Hawk.get(SPKey.SP_KEY_USER_MY_INFO);
        String localUserId = "";
        if (personalBean != null) {
            localUserId = personalBean.getUserId() + "";
        }
        chatAdapter = new ChatAdapter(null, localUserId);
        videoChatRecycler.setAdapter(chatAdapter);
        chatAdapter.setEmptyView(R.layout.layout_empty_view, videoChatRecycler);
        chatAdapter.isUseEmpty(false);
    }


    @Override
    public void initData() {
        loadCache();
        new Handler().postDelayed(() -> refreshLayout.autoRefresh(), 1000);
    }

    /**
     * 预加载缓存数据
     */
    private void loadCache() {
        String channelStr = Hawk.get("video-chat-channel", null);
        String userStr = Hawk.get("video-chat-user", null);
        if (channelStr != null && userStr != null) {
            initCacheData(JSON.parseArray(channelStr, ChannelListBean.class), JSON.parseObject(userStr, MLUserList.class));
        }
    }

    private void initCacheData(List<ChannelListBean> channelListBeanList, MLUserList mlUserList) {
        //初始化频道数据
        if (channelListBeanList != null) {
            if (page == 1 && chatAdapter.getData() != null) {
                chatAdapter.getData().clear();
            }
            ChatTabBean chatTabBean = new ChatTabBean();

            List<ChatListDataBean> list = new ArrayList<>();

            for (ChannelListBean channelListBean : channelListBeanList) {
                ChatListDataBean chatListDataBean = new ChatListDataBean(channelListBean.getId(), channelListBean.getChannelName(), channelListBean.getImgUrl());
                list.add(chatListDataBean);
            }
            chatTabBean.setChatTabListData(list);
            chatAdapter.addData(chatTabBean);

        }
        //初始化主播数据
        if (mlUserList != null) {
            onUserListSuccess(mlUserList);
        }
    }

    /**
     * 滑动页面至顶部并刷新数据
     */
    public void refresh() {
        if (chatAdapter != null && chatAdapter.getData() != null && chatAdapter.getData().size() > 0) {
            videoChatRecycler.scrollToPosition(0);
        }
        refreshLayout.autoRefresh();
    }

    @Override
    public void setData(@Nullable Object data) {


    }

    //一般不带参数的跳转activity
    public void intentAc(Class<?> cls) {
        Intent intent = new Intent(getActivity(), cls);
        startActivity(intent);
    }

    @Override
    public void onChannelListSuccess(List<ChannelListBean> channelListBeanList) {
        if (channelListBeanList != null) {
            Hawk.put("video-chat-channel", JSON.toJSONString(channelListBeanList));
        }
        errorView.setVisibility(View.GONE);
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if (page == 1 && chatAdapter.getData() != null) {
            chatAdapter.getData().clear();
        }
        ChatTabBean chatTabBean = new ChatTabBean();

        List<ChatListDataBean> list = new ArrayList<>();

        for (ChannelListBean channelListBean : channelListBeanList) {
            ChatListDataBean chatListDataBean = new ChatListDataBean(channelListBean.getId(), channelListBean.getChannelName(), channelListBean.getImgUrl());
            list.add(chatListDataBean);
        }
        chatTabBean.setChatTabListData(list);
        chatAdapter.addData(chatTabBean);

        chatAdapter.isUseEmpty(!(chatAdapter.getData().size() > 0));
        mPresenter.getMlList(1, 20, 1, null, null, null);
    }

    @Override
    public void onChannelListFailed(String error) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if (chatAdapter.getData() != null) {
            chatAdapter.getData().clear();
        }
        errorView.setVisibility(View.VISIBLE);
    }

    @Override
    public void onUserListSuccess(MLUserList userList) {
        if (userList != null) {
            Hawk.put("video-chat-user", JSON.toJSONString(userList));
        }
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        VideoChatBean videoChatBean = new VideoChatBean();
        List<VideoChatListBean> list = new ArrayList<>();

        for (MLUserList.ListBean u : userList.getList()) {
            String price = u.getSoundsVideoStatus() == 1 ? (u.getGsLiveGrade().getVoicePrice() + "豆/分钟") : (u.getGsLiveGrade().getVideoPrice() + "豆/分钟");
            int voiceLen = 0;
            String voicePath = null;
            if (u.getVoiceFile() != null) {
                voiceLen = u.getVoiceFile().getFileLength();
                voicePath = u.getVoiceFile().getFilePath();
            }
            VideoChatListBean videoChatListBean = new VideoChatListBean(price, voiceLen, u.getHeadimg(), u.getResidence(), u.getHeadimg(), u.getGeneration(), u.getAge() + "", u.getGsName(), u.getSoundsVideoStatus(), u.getVideoDetails(), String.valueOf(u.getSex()), u.getHeadimg(), voicePath);
            videoChatListBean.setUserId(u.getUserId());
            videoChatListBean.setPrice(u.getSoundsVideoStatus() == 1 ? (u.getGsLiveGrade().getVoicePrice()) : (u.getGsLiveGrade().getVideoPrice()));
            list.add(videoChatListBean);
        }
        videoChatBean.setRecommendBeans(list);

        if (userList.getList() != null && userList.getList().size() != 0) {
            chatAdapter.addData(videoChatBean);
        } else {
            refreshLayout.finishLoadMoreWithNoMoreData();
        }
    }

    @Override
    public void onUserListFailed(String error) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
    }

    @Override
    public void onAdvertSuccess(AdvertBean advertBean) {

    }

    @Override
    public void onAdvertSuccessFailed(String error) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (chatAdapter.countDownTimer != null) {
            chatAdapter.countDownTimer.cancel();
        }
    }
}
